<template>
  <!-- 编辑班级信息组件 :visible.sync显示侧边栏 direction侧边栏打开方向 -->
  <el-drawer :visible.sync="showDrawer" title="编辑信息" direction="rtl" size="40%">
    <el-form :model="editCollege" status-icon :rules="rules" ref="editCollege" label-width="100px">
      <el-form-item label="学院号" prop="collegeId">
        <el-input type="text" v-model="editCollege.collegeId" autocomplete="off" :disabled="true" />
      </el-form-item>
      <el-form-item label="学院" prop="college">
        <el-input type="text" v-model="editCollege.college" autocomplete="off" :disabled="true" />
      </el-form-item>
      <el-form-item label="班级号" prop="id">
        <el-input type="text" v-model="editCollege.id" autocomplete="off" :disabled="true" />
      </el-form-item>
      <el-form-item label="班级" prop="major">
        <el-input type="text" v-model="editCollege.major" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('editCollege')">提交</el-button>
        <el-button @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script>
import { getDetail, updateMajor } from '@/api/college'

export default {
  name: 'editMajorPage', // 编辑班级页面
  data () {
    return {
      showDrawer: false, // 显示侧边栏true
      // 存放编辑班级的信息
      editCollege: {
        major: '',
        id: '',
        college: '',
        collegeId: ''
      },
      // 设置对应的校验规则
      rules: {
        id: [
          { required: true, message: '请输入班级号', trigger: 'blur' },
          { pattern: /^\d{4}$/, message: '班级号必须为4位数字', trigger: 'blur' }
        ],
        major: [{ required: true, message: '请输入专业名', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 显示弹层
    async openDrawer (row) {
      this.showDrawer = true
      const { data: { data } } = await getDetail(row.collegeId, row.id)
      this.editCollege = data
    },
    // 提交表单 发送请求
    submitForm (editCollege) {
      // 校验数据是否合法
      this.$refs[editCollege].validate(async (valid) => {
        if (valid) {
          // 发送update请求前需要将editCollege中的id属性名替换为majorId
          this.$set(this.editCollege, 'majorId', this.editCollege.id)
          this.$delete(this.editCollege, 'id')
          await updateMajor(this.editCollege)
          this.$message.success('编辑成功')
          // 编辑成功后关闭侧边栏并通知父组件更新页面
          this.showDrawer = false
          this.$emit('successEdit')
        }
      })
    },
    // 重置表单
    async resetForm () {
      const { data: { data } } = await getDetail(this.editCollege.collegeId, this.editCollege.id)
      this.editCollege = data
    }
  }
}
</script>

<style></style>
